package cn.rayland.library.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import cn.rayland.library.stm32.IIC;

import android.os.Handler;
import android.os.Looper;
import android_serialport_api.SerialPort;

public class SerialPortReader {
	private static SerialPort serialPort;
	private static InputStream inputStream;
	private static ReadSerialPortThread readThread;
	private static IIC stm32 = IIC.getInstance();

	public static void init(MachineManager manager) {
		if (stm32 == null) {
			System.err.println("stm32 not found");
			return;
		}
		if (serialPort == null) {
			try {
				serialPort = new SerialPort(new File("/dev/ttyS1"), 115200, 0);
				inputStream = serialPort.getInputStream();
				readThread = new ReadSerialPortThread(manager);
				readThread.start();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private static class ReadSerialPortThread extends Thread {
		private MachineManager manager;
		private Handler uiHandler;

		public ReadSerialPortThread(MachineManager machineManager) {
			this.manager = machineManager;
			uiHandler = new Handler(Looper.getMainLooper());
		}

		@Override
		public void run() {
			super.run();
			while (!isInterrupted()) {
				int size;
				try {
					byte[] xyzData = new byte[64];
					if (inputStream == null)
						return;
					size = inputStream.read(xyzData);
					if (size > 0) {
						final float[] positions = new float[3];
						positions[0] = (float) (FormatUtils
								.byte2int(new byte[] { xyzData[0], xyzData[1],
										xyzData[2], xyzData[3] }) / manager.machine.axis_x.steps_per_mm);
						positions[1] = (float) (FormatUtils
								.byte2int(new byte[] { xyzData[4], xyzData[5],
										xyzData[6], xyzData[7] }) / manager.machine.axis_y.steps_per_mm);
						positions[2] = (float) (FormatUtils
								.byte2int(new byte[] { xyzData[8], xyzData[9],
										xyzData[10], xyzData[11] }) / manager.machine.axis_z.steps_per_mm);
						uiHandler.post(new Runnable() {
							public void run() {
								if (X3gExecutors.state.getTask() != null
										&& X3gExecutors.state.getTask()
												.getGcodeCallback() != null) {
									X3gExecutors.state.getTask()
											.getGcodeCallback()
											.onM114(positions);
								}
							}
						});

						byte[] byte2 = new byte[2];
						byte2[0] = 0;
						byte2[1] = 1;
						stm32.sendData(byte2, 0, byte2.length);
					}
				} catch (IOException e) {
					e.printStackTrace();
					return;
				}
			}
		}
	}
	
	public static void destory(){
		if(serialPort!=null){
			serialPort.close();
			serialPort = null;
		}
		if(readThread!=null){
			readThread.interrupt();
		}
		inputStream = null;
	}

}
